# -*- coding: UTF-8 -*-
"""
@Time:2022/5/13 10:36
@File:dynamic.py
@Author:常雷
@Software:PyCharm
"""
from django.db.models import When,F,Case,CharField
import datetime
from rest_framework.response import Response
from django.shortcuts import render, HttpResponse
from rest_framework import serializers
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView, ListAPIView, RetrieveAPIView
from palyWordDackend import models
from django.forms import model_to_dict
from rest_framework import status
from django.db.models import F
import uuid
import requests
import re

class UserInfoViewModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.UserInfo
        fields = ['username','id','is_active']
        # fields = "__all__"


class TagViewModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Tag
        fields = "__all__"

class CategoryViewModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Category
        fields = "__all__"

class RecommendationView(APIView):
    def get(self,request,*args,**kwargs):
        data = {}
        user_queryset = models.UserInfo.objects.order_by('-is_active')[0:4]
        ser_user = UserInfoViewModelSerializer(instance=user_queryset, many=True)
        data['users'] = ser_user.data

        tag_queryset = models.Tag.objects.order_by('-hot_count')[0:4]
        ser_tag = TagViewModelSerializer(instance=tag_queryset, many=True)
        data['tags'] = ser_tag.data

        category_queryset = models.Category.objects.order_by('-hot_count')[0:4]
        ser_category = CategoryViewModelSerializer(instance=category_queryset, many=True)
        data['category'] = ser_category.data

        return Response(data,status=status.HTTP_200_OK)

    def post(self,request,*args,**kwargs):
        value = request.data.get('value')
        if value:
            data = {}
            case = Case(
                When(title=value, then=1),
                When(title__endswith=value, then=2),
                When(title__startswith=value, then=3),
                When(title__contains=value, then=4),
                default=5,
                output_field=CharField()
            )
            print(value)
            article_queryset = models.Article.objects.filter(title__contains=value).annotate(pos=case).order_by('pos')[0:10]
            ser_article = PostRecommendationViewModelSerializer(instance=article_queryset, many=True)
            # data['articles'] = ser_article.data
            return Response(ser_article.data, status=status.HTTP_200_OK)
        else:
            return Response({'code':201, 'msg':'没有搜索内容'}, status=status.HTTP_200_OK)

class PostRecommendationViewModelSerializer(serializers.ModelSerializer):
    user = serializers.SerializerMethodField()
    category = serializers.SerializerMethodField()

    viewer = serializers.SerializerMethodField()

    comment = serializers.SerializerMethodField()
    tags = serializers.SerializerMethodField()

    class Meta:
        model = models.Article
        fields = "__all__"
        # exclude = ['cover']

    # def get_images(self, obj):
    #     # 找到当前新闻的所有图片对象
    #     detail_queryset = models.ArticleDetail.objects.filter(Article=obj)
    #     # return [row.cos_path for row in detail_queryset]
    #     # return [{"id":row.id, "path":row.cos_path} for row in detail_queryset]
    #     return [model_to_dict(row, ['id', 'cos_path']) for row in detail_queryset]

    def get_create_date(self, obj):
        return obj.create_date.strftime("%Y-%m-%d %H:%M")

    def get_user(self, obj):
        # model_to_dict fields:需要字段列表,exclude:不需要字段
        return model_to_dict(obj.user, fields=['id', 'username', 'avatar'])

    def get_category(self, obj):
        if obj.category:
            return model_to_dict(obj.category, fields=['id', 'name'])

    def get_tags(self, obj):
        tag_queryset = models.Article2Tag.objects.filter(article=obj).order_by('-id')
        queryset = models.Article2Tag.objects.filter(article=obj.id)
        context = {
            'count': queryset.count(),
            'result': [model_to_dict(row.tag, ['name', 'hot_count']) for row in tag_queryset]
        }
        return context

    def get_viewer(self, obj):
        viewer_queryset = models.ViewerRecord.objects.filter(news=obj).order_by('-id')[0:10]
        queryset = models.ViewerRecord.objects.filter(news=obj.id)
        context = {
            'count': queryset.count(),
            'result': [model_to_dict(row.user, ['username', 'avatar']) for row in viewer_queryset]
        }
        return context

    #
    def get_comment(self, obj):
        """
        # 获取所有的1级评论。再給每个1级评论获取一个二级评论。
        :param obj:
        :return:
        """
        # 1 获取所有的1级评论
        first_queryset = models.Comment.objects.filter(article=obj, depth=1).order_by('id')[0:10].values(
            'id',
            'content',
            'depth',
            'user__username',
            'user__avatar',
            'comment_time'
        )
        first_id_list = [item['id'] for item in first_queryset]
        # 2 获取所有的2级评论
        # second_queryset = models.Comment.objects.filter(Article=obj, depth=2)
        # 2 获取所有一级评论的2级评论
        # second_queryset = models.Comment.objects.filter(Article=obj, depth=2, reply_id__in=first_id_list)
        # 2 获取所有一级评论的2级评论(每个二级评论只取一条,最新或者最热)
        from django.db.models import Max
        result = models.Comment.objects.filter(article=obj, depth=2, reply_id__in=first_id_list).values(
            'reply_id').annotate(max_id=Max('id'))
        # print(result)<QuerySet [{'reply_id': 1, 'max_id': 5}, {'reply_id': 8, 'max_id': 12}]>
        second_id_list = [item['max_id'] for item in result]
        second_queryset = models.Comment.objects.filter(id__in=second_id_list).values(
            'id',
            'content',
            'depth',
            'user__username',
            'user__avatar',
            'comment_time',
            'reply_id',
            'reply__user__username'
        )
        # print(second_queryset)
        import collections
        first_dict = collections.OrderedDict()
        for item in first_queryset:
            item['comment_time'] = item['comment_time'].strftime('%Y-%m-%d %H:%M')
            first_dict[item['id']] = item
        for node in second_queryset:
            node['comment_time'] = node['comment_time'].strftime('%Y-%m-%d %H:%M')
            first_dict[node['reply_id']]['child'] = [node, ]
        return first_dict.values()